package github.javaguide.loadbalance.loadbalancer;

import github.javaguide.loadbalance.AbstractLoadBalance;
import github.javaguide.remoting.dto.RpcRequest;

import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Implementation of random load balancing strategy
 *
 * @author shuang.kou
 * @createTime 2020年06月21日 07:47:00
 */
public class LoadBalance extends AbstractLoadBalance {
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public final  int getAndIncrement(){
        int current;
        int next;
        do{
            current=this.atomicInteger.get();
            next=current>=214748364?0:current+1;
        }while (!this.atomicInteger.compareAndSet(current,next));
        System.out.println("next:"+next);
        return next;
    }
    @Override
    protected String doSelect(List<String> serviceAddresses, RpcRequest rpcRequest) {
        int i = getAndIncrement() % serviceAddresses.size();
        return serviceAddresses.get(i);
    }
}
